package com.siashan.unipay4j.wx.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.siashan.unipay4j.core.IPayConfig;
import com.siashan.unipay4j.core.Result;
import com.siashan.unipay4j.core.pay.PayModel;
import com.siashan.unipay4j.wx.model.UnifiedOrderModel;
import com.siashan.unipay4j.wx.sdk.WXPayConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信Native支付
 * 用户扫描商户展示在各种场景的二维码进行支付
 *
 * @author siashan
 * @since v1.0.1
 **/
@Slf4j
public class WxPayNative extends WxPay {

    public WxPayNative() {
        super();
    }

    public WxPayNative(IPayConfig payConfig) {
        super(payConfig);
    }

    @Override
    public String loadV3PayUrl() {
        return WXPayConstants.V3_PAY_URL_NATIVE;
    }

    /**
     * 支付
     *
     * @param model  支付参数
     * @return 支付结果
     */
    @Override
    public Result pay(PayModel model) {
        return doPay(model, WxTradeTypeEnum.NATIVE);
    }


    /**
     * 是否需要openId参数
     *
     * @return 是否需要
     */
    @Override
    public boolean needOpenId() {
        return false;
    }

    /**
     * 处理交易成功逻辑
     *
     * @param r  报文
     * @return 返回结果
     * @throws Exception
     */
    @Override
    public Result doTradeSuccess(Map<String, String> r) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("code_url", r.get("code_url"));
        return Result.tradeSuccess(map);
    }

    /**
     * 处理交易成功逻辑
     *
     * @param body  报文
     * @param orderModel 下单参数
     * @return 返回结果
     */
    @Override
    public Result doTradeSuccessV3(String body, UnifiedOrderModel orderModel) {
        JSONObject bodyJson = JSON.parseObject(body);
        String codeUrl = bodyJson.getString("code_url").trim();
        Map<String, Object> map = new HashMap<>(2);
        map.put("code_url", codeUrl);
        return Result.tradeSuccess(map);
    }
}
